package pl.edu.agh.to1.dice.logic;

import java.util.*;
import java.lang.String;
import java.io.*;

public class FileRankingManager extends RankingManager{
	private String path;

	public FileRankingManager(String spath,Comparator<RankingEntry> cm){
		super(cm);		
		this.path = spath;
	}

	public void load(){
		try{
			reset();
			BufferedReader in = new BufferedReader(new FileReader(path));
			String line = in.readLine();
			while(line != null){
				String [] tmp = line.split(" ");
				
				if(tmp.length > 2){
					String name = tmp[0];
					int sum = Integer.parseInt(tmp[1]);
					int best = Integer.parseInt(tmp[2]);
					int games = Integer.parseInt(tmp[3]);
					RankingEntry en = new RankingEntry(name,sum,best,games);
					addEntry(en);
				}
				line = in.readLine();
			}
			update();
			in.close();
		}
		catch(Exception e){
			System.err.println("error");
		}
	}
	
	protected void save(){
		try{
			FileWriter wr = new FileWriter(path);
			BufferedWriter out = new BufferedWriter(wr);
			for(RankingEntry re : entries){
					out.write(re.toString());	
					out.write("\n");
			}
			out.close();
		}
		catch(Exception e){
			System.err.println("error");
		}
	}
}
